from flask import Blueprint, render_template, redirect, url_for, session, request, json, jsonify
from form import InsertForm, DeleteForm, UpdateForm, Get_object_idForm, SelectForm, Fl_showForm, ShowForm, YmForm
from werkzeug.security import generate_password_hash, check_password_hash
from models import UserModel, ObjectModel, HistoryModel
from exts import db
from werkzeug.datastructures import ImmutableMultiDict
from datetime import datetime

bp = Blueprint("object",__name__,url_prefix="/object")
rootpath = "D:/python flask project/project"

@bp.route("/insert", methods=['Get', 'Post'])
def insert():
    if request.method == 'GET':
        return {
            "state": False,
            "message": "请增加物品"  # 返回登录页面
        }
    else:
        form = InsertForm(ImmutableMultiDict(request.form))
        if form.validate():
            user = UserModel.query.filter_by(id=request.form['user_id']).first()
            if not user:
                return {
                    "state": False,
                    "message": "该用户不存在"
                }
            objectname = request.form['objectname']
            price = request.form['price']
            count = request.form['count']
            classfication = request.form['classfication']
            user_id = request.form['user_id']
            maturity_time = request.form['maturity_time']
            place = request.form['place']
            remarks = request.form['remarks']
            picture = request.form['picture']
            # path = rootpath + "/public/images/objects/" + img.filename
            # picture = img.filename
            # img.save(path)
            # user_id = request.form['user_id']
            object = ObjectModel.query.filter_by(objectname=objectname, user_id=user_id).first()
            if not object:
                object2 = ObjectModel(objectname=objectname, count=count,  price=price, classfication=classfication, user_id=user_id, picture=picture,
                                      maturity_time=maturity_time, place=place, remarks=remarks)
                db.session.add(object2)
                db.session.commit()
                object_id = object2.object_id
                return {
                    "state": True,
                    "object_id": object_id,
                    "message": "insert object success"
                }
            else:
                return {
                    "state": False,
                    "message": "该物品已存在"  # 返回增加页面
                }
        else:
            return {
                "state": False,
                "message": form.errors  # 返回登录页面
            }

@bp.route("/delete", methods=['Get', 'Post'])
def delete():
    if request.method == 'GET':
        return {
            "state": False,
            "message": "请填写要删除的物品"  # 返回登录页面
        }
    else:
        json = request.json
        form = DeleteForm(ImmutableMultiDict(json))
        if form.validate():
            user_id = json.get('user_id')
            user = UserModel.query.filter_by(id=user_id).first()
            if not user:
                return {
                    "state": False,
                    "message": "该用户不存在"
                }
        objectname = json.get('objectname')
        user_id = json.get('user_id')
        object = ObjectModel.query.filter_by(user_id=user_id, objectname=objectname).first()
        if not object:
            return {
                "state": False,
                "message": "物品不存在"
            }
        db.session.delete(object)
        db.session.commit()
        return {
            "state": True,
            "message": "物品删除成功"  # 返回增加页面
        }
        # else:
        #     return {
        #         "state": False,
        #         "message": form.errors  # 返回登录页面
        #     }
    # # #表单验证：flask-wtf
    # form = RegisterForm(request.form)
    # if form.validate():
    #     email = form.email.data
    #     username = form.username.data
    #     password = form.password.data
    #     wechat = form.wechat.data
    #     user = Usermodel(email=email,username=username,password=generate_password_hash(password),wechat=wechat)
    #     db.session.add(user)
    #     db.session.commit()
    #     return redirect(url_for("user.login"))  # 跳转到登录页面
    # else:
    #     return "注册失败" # 返回注册页面

@bp.route("/update", methods = ["GET", "POST"])
def update():
    if request.method == 'GET':
        return {
            "state": False,
            "message": "请修改物品"  # 返回登录页面
        }
    else:
        form = UpdateForm(ImmutableMultiDict(request.form))
        if form.validate():
            objectname = request.form['objectname']
            price = request.form['price']
            count = request.form['count']
            classfication = request.form['classfication']
            object_id = request.form['object_id']
            maturity_time = request.form['maturity_time']
            place = request.form['place']
            remarks = request.form['remarks']
            picture = request.form['picture']
            # user_id = request.form['user_id']
            object = ObjectModel.query.filter_by(object_id=object_id).first()
            # img.close()
            if not object:
                return {
                    "state": False,
                    "message": "该物品不存在"
                }
            else:
                object.objectname = objectname
                object.price = price
                object.count = count
                object.classfication = classfication
                object.maturity_time = maturity_time
                object.place = place
                object.remarks = remarks
                object.picture = picture
                # path = rootpath + "/public/images/objects/" + img.filename
                # img.save(path)
                db.session.commit()
                return {
                    "state": True,
                    "message": "update object success"  # 返回增加页面
                }
        else:
            return {
                "state": False,
                "message": form.errors  # 返回登录页面
            }


@bp.route("/get_object_id", methods = ["POST"])
def get_object_id():
    json = request.json
    form = Get_object_idForm(ImmutableMultiDict(json))
    if form.validate():
        user_id = json.get('user_id')
        user = UserModel.query.filter_by(id=user_id).first()
        if not user:
            return {
                "state": False,
                "message": "该用户不存在"
            }
    objectname = json.get('objectname')
    user_id = json.get('user_id')
    object = ObjectModel.query.filter_by(user_id=user_id, objectname=objectname).first()
    if not object:
        return {
            "state": False,
            "message": "物品不存在"
        }
    else:
        object_id = object.object_id
        return{
            "state": True,
            "message": "查询成功",
            "object_id": object_id
        }

@bp.route("/select", methods=['Get', 'Post'])
def select():
    if request.method == 'GET':
        return {
            "state": False,
            "message": "请点击物品"  # 返回登录页面
        }
    else:
        json = request.json
        form = SelectForm(ImmutableMultiDict(json))
        if form.validate():
            user_id = json.get('user_id')
            object_id = json.get('object_id')
            user = UserModel.query.filter_by(id=user_id).first()
            if not user:
                return {
                    "state": False,
                    "message": "该用户不存在"
                }
            object = ObjectModel.query.filter_by(object_id=object_id, user_id=user_id).first()
            if not object:
                return {
                    "state": False,
                    "message": "物品不存在"
                }
            else:
                object_name=object.objectname
                search = HistoryModel.query.filter_by(object_id=object_id).first()
                if not search:
                    history_search = HistoryModel(object_id=object_id, user_id=user_id, objectname=object_name)
                    db.session.add(history_search)
                    db.session.commit()
                return {
                    "object_id": object.object_id,
                    "objectname": object.objectname,
                    "count": object.count,
                    "price": object.price,
                    "img": object.picture,
                    "classfication": object.classfication,
                    "maturity_time": object.maturity_time.isoformat(),
                    "place": object.place,
                    "remarks": object.remarks
                }
        else:
            return {
                "state": False,
                "message": form.errors  # 返回登录页面
            }


# 物品转json
def object_to_json(items):
    objects = []
    for item in items:
        object1 = ObjectModel.query.filter_by(object_id=item.object_id).first()
        iso_date_str = object1.maturity_time.isoformat()
        object = {
            "object_id": item.object_id,
            "objectname": item.objectname,
            "count": item.count,
            "price": item.price,
            "img": object1.picture,
            "classfication": item.classfication,
            "maturity_time": object1.maturity_time.isoformat(),
            "place": item.place,
            "remarks": item.remarks
        }
        objects.append(object)
    return jsonify(objects)

@bp.route("/fl_show", methods=["POST"])
def fl_show():
    json = request.json
    form = Fl_showForm(ImmutableMultiDict(json))
    if form.validate():
        user_id = json.get('user_id')
        user = UserModel.query.filter_by(id=user_id).first()
        if not user:
            return {
                "state": False,
                "message": "该用户不存在"
            }
    classfication = json.get('classfication')
    user_id = json.get('user_id')
    user = UserModel.query.filter_by(id=user_id).first()
    objects = user.objects
    objects = sorted(objects, key=lambda p: str(p.maturity_time), reverse=True)
    fl_object = []
    for item in objects:
        if item.classfication == classfication:
            fl_object.append(item)
    objects_json = object_to_json(fl_object)
    return objects_json

@bp.route("/show", methods=["POST"])
def show():
    json = request.json
    form = ShowForm(ImmutableMultiDict(json))
    if form.validate():
        user_id = json.get('user_id')
        user = UserModel.query.filter_by(id=user_id).first()
        if not user:
            return {
                "state": False,
                "message": "该用户不存在"
            }
    user_id = json.get('user_id')
    user = UserModel.query.filter_by(id=user_id).first()
    objects = user.objects
    objects = sorted(objects, key=lambda p: str(p.maturity_time), reverse=True)
    objects_json = object_to_json(objects)
    return objects_json

@bp.route("/proportion", methods=["POST"])
def proportion():
    json = request.json
    form = ShowForm(ImmutableMultiDict(json))
    if form.validate():
        user_id = json.get('user_id')
        user = UserModel.query.filter_by(id=user_id).first()
        if not user:
            return {
                "state": False,
                "message": "该用户不存在"
            }
    classfications = ["食物", "日用品", "化妆品", "图书", "衣服", "其他"]
    user_id = json.get('user_id')
    user = UserModel.query.filter_by(id=user_id).first()
    objects = user.objects
    length = []
    for i in range(len(classfications)):
        fl_object = []
        for item in objects:
            if item.classfication == classfications[i]:
                fl_object.append(item)
        length.append(len(fl_object))
    all = 0
    for i in length:
        all = all + i
    if all == 0:
        return {
            "食物": 0,
            "日用品": 0,
            "化妆品": 0,
            "图书": 0,
            "衣服": 0,
            "其他": 0
        }
    all = all / 100
    return {
        "食物": round(length[0] / all, 2),
        "日用品": round(length[1] / all, 2),
        "化妆品": round(length[2] / all, 2),
        "图书": round(length[3] / all, 2),
        "衣服": round(length[4] / all, 2),
        "其他": round(length[5] / all, 2)
    }

def object1_to_json(items):
    objects = []
    for item in items:
        object1=ObjectModel.query.filter_by(object_id=item.object_id).first()
        object = {
            "objectname": item.objectname,
        }
        objects.append(object)
    return jsonify(objects)


@bp.route("/get_history_search", methods = ["POST"])
def get_history_search():
    json = request.json
    form = ShowForm(ImmutableMultiDict(json))
    if form.validate():
        user_id = json.get('user_id')
        user = UserModel.query.filter_by(id=user_id).first()
        if not user:
            return {
                "state": False,
                "message": "该用户不存在"
            }
        search = UserModel.query.filter_by(id=user_id).first()
        objects = search.history_search
        objects_json = object1_to_json(objects)
        return objects_json

@bp.route("/get_ym", methods = ["POST"])
def get_ym():
    json = request.json
    form = YmForm(ImmutableMultiDict(json))
    if form.validate():
        user_id = json.get('user_id')
        user = UserModel.query.filter_by(id=user_id).first()
        if not user:
            return {
                "state": False,
                "message": "该用户不存在"
            }
        maturity_time = json.get('maturity_time')
        user_id = json.get('user_id')
        user = UserModel.query.filter_by(id=user_id).first()
        objects = user.objects
        objects = sorted(objects, key=lambda p: str(p.maturity_time), reverse=True)
        fl_object = []
        for item in objects:
            time = str(item.maturity_time)
            # print(time[0:7])
            if time[0:7] == maturity_time:
                fl_object.append(item)
        objects_json = object_to_json(fl_object)
        return objects_json